package cn.zmit.kuxi.activity;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.contants.Constants;
import cn.zmit.kuxi.contants.Response;
import cn.zmit.kuxi.request.RequestTask;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.xdroid.common.utils.StringUtils;
import com.xdroid.common.utils.ToastUtils;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;

/** * @author @parameter * @return */
public class RegisteredActivity extends BaseActivity {
	@ViewInject(R.id.edt_iput_phone_number)
	private EditText iput_phone_number;
	@ViewInject(R.id.et_inpu_verification_code)
	private EditText inpu_verification_code;
	@ViewInject(R.id.tv_get_verification_code)
	private TextView tv_get_verification_code;
	@ViewInject(R.id.tv_regsit_login)
	private TextView tv_regsit_login;
	@ViewInject(R.id.btn_next)
	private Button btn_next;
	@ViewInject(R.id.llRoot)
	private LinearLayout llRoot;
	private String phone_number;
	private String verification_code;
	private String flag, type;
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constants.EXECUTE_LOADING:
				tv_get_verification_code.setText(msg.arg1 + "秒后重新获取");
				if (msg.arg1 == 0) {
					closeTimer();
					tv_get_verification_code.setTextColor(getResources()
							.getColor(R.color.white));
					tv_get_verification_code.setClickable(true);
				}
				break;
			case Constants.EXECUTE_FINISH:
				tv_get_verification_code.setText("重新获取验证码");
				tv_get_verification_code.setTextColor(getResources().getColor(
						R.color.white));
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_registered);
		ViewUtils.inject(this);
		flag = getTextFromBundle("flag");
		llRoot.setOnTouchListener(new OnTouchListener() {

			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

				return inputMethodManager.hideSoftInputFromWindow(
						getCurrentFocus().getWindowToken(), 0);
			}
		});
	}

	@OnClick({ R.id.tv_regsit_login, R.id.tv_get_verification_code,
			R.id.btn_next })
	private void OnClick(View v) {
		switch (v.getId()) {
		case R.id.tv_regsit_login:
			openActivity(LoginActivity.class);
			break;
		case R.id.tv_get_verification_code:
			if (checkForm()) {
				phone_number = iput_phone_number.getText().toString().trim();
				if (flag.equals("register")) {
					type = "1";
					// 动态码请求
					doSalt(phone_number, type);
				}
			}

			break;
		case R.id.btn_next:
			if (checkForm()) {
				phone_number = iput_phone_number.getText().toString().trim();
				verification_code = inpu_verification_code.getText().toString()
						.trim();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("phone", phone_number);
				map.put("salt", verification_code);
				RequestTask.getInstance().doCommitSalt(this, map,
						new OnCommitRequestListener());
			}

			break;
		default:
			break;
		}
	}

	private void doSalt(String phone, String type) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("phone", phone);
		map.put("type", type);
		RequestTask.getInstance().doSalt(this, map, new OnRequestListener());

	}

	private String code_back;

	private class OnCommitRequestListener extends
			OnRequestListenerAdapter<Object> {

		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			super.onDone(request, response, dataType);
			JsonData jsonData = JsonData.create(response);
			// code_back = jsonData.optString(Response.CODE);
			if (jsonData.optString(Response.CODE).equals("0")) {
				Bundle bundle = new Bundle();
				bundle.putString("phone", phone_number);
				openActivity(RegisteredTwoActivity.class, bundle);

			} else {
				ToastUtils.show(context, jsonData.optString("message"));
			}
		}
	}

	/**
	 * 请求监听
	 * 
	 * @return
	 */
	private String data;

	private class OnRequestListener extends OnRequestListenerAdapter<Object> {

		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);

			JsonData jsonData = JsonData.create(response);
			data = jsonData.optString("code");
			if (data != null && data.equals("0")) {
				ToastUtils.show(context, jsonData.optString("message"));

				// 请求结束开启倒计时
				inpu_verification_code.setTextColor(getResources().getColor(
						R.color.black));
				inpu_verification_code.setClickable(false);

				startTimer();

			} else if (jsonData.optString(Response.CODE).equals("1")) {
				ToastUtils.show(context, jsonData.optString("message"));
			} else if (jsonData.optString(Response.CODE).equals("2")) {
				ToastUtils.show(context, jsonData.optString("message"));
			} else if (jsonData.optString(Response.CODE).equals("3")) {
				ToastUtils.show(context, jsonData.optString("message"));
			}

		}

		@Override
		public void onRequestFailed(String error) {
			super.onRequestFailed(error);
		}

		@Override
		public void onRequestPrepare() {
			super.onRequestPrepare();
		}
	}

	private Boolean checkForm() {
		phone_number = iput_phone_number.getText().toString().trim();
		verification_code = inpu_verification_code.getText().toString().trim();
		if (StringUtils.isEmpty(phone_number)) {
			ToastUtils.show(context, "手机号不能为空");
			return false;
		} else if (!StringUtils.isPhone(phone_number)) {
			ToastUtils.show(context, "请输入合法的手机号");
			return false;
		}
		return true;
	}

	// 开启倒计时
	private int mTimerId = 120;

	private TimerTask timerTask;

	private Timer timer;

	public void startTimer() {
		if (timerTask == null) {
			timerTask = new TimerTask() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					Message msg = new Message();
					msg.what = Constants.EXECUTE_LOADING;
					msg.arg1 = (int) (--mTimerId);
					handler.sendMessage(msg);
				}
			};
			timer = new Timer();
			timer.schedule(timerTask, 100, 1000);
		}
	}

	// 结束计时
	private void closeTimer() {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (timerTask != null) {
			timerTask = null;
		}
		mTimerId = 120;
		handler.sendEmptyMessage(Constants.EXECUTE_FINISH);
	}

}
